const os = require('os');
const diskinfo = require('diskinfo')
const cpuStat = require('cpu-stat');

LB.HELPER.SYSINFO = {}
var unitConvert = (m,n)=>{      //容量单位换算
    var TB=0,GB = 0,MB = 0,KB = 0;
    (m>(1<<30))&&(GB=(m/(1<<30)).toFixed(n));
    (m>(1<<20))&&(m<(1<<30))&&(MB=(m/(1<<20)).toFixed(n));
    (m>(1<<10))&&(m>(1<<20))&&(KB=(m/(1<<10)).toFixed(n));
    return TB>0?TB+'TB':GB>0?GB+'GB':MB>0?MB+'MB':KB>0?KB+'KB':m+'B';
}

setInterval(()=>{   //间隔运行，防undefined
    cpuStat.usagePercent(function(err, pre, sec) {
        if (err) {
            return
        }
        LB.HELPER.SYSINFO.cpuUsage = pre.toFixed(2)+"%"
    })

    LB.HELPER.SYSINFO.memUsage = unitConvert(os.totalmem()-os.freemem(),2)+"/"+unitConvert(os.totalmem(),0)+"("+(((os.totalmem()-os.freemem()) / os.totalmem())*100).toFixed(1)+"%)"

    var current_disk = __dirname.substr(0,2).toLowerCase();
    diskinfo.getDrives(function(err, aDrives) {
        if(err){
            LB.HELPER.SYSINFO.diskUsage = "查询失败，请稍后重试"
            return
        }
        if(aDrives.some((val) => val.mounted.toLowerCase()===current_disk)){
            let s = aDrives.indexOf(aDrives.filter(d=>d.mounted.toLowerCase() === current_disk)[0]);
            LB.HELPER.SYSINFO.diskUsage = unitConvert((aDrives[s].used),2) + "/"+unitConvert((aDrives[s].blocks),0) + "（"+aDrives[s].capacity+"）";
        }
    })

    let day = Math.floor( os.uptime()/ (24*3600) ); // Math.floor()向下取整 
    let hour = Math.floor( (os.uptime() - day*24*3600) / 3600); 
    let minute = Math.floor( (os.uptime() - day*24*3600 - hour*3600) /60 ); 
    let second = os.uptime() - day*24*3600 - hour*3600 - minute*60;
    LB.HELPER.SYSINFO.sysUptime = day + "天"  + hour + "小时" + minute + "分" + second + "秒"
},1000)